package com.ruoyi.workFlow.service.impl;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.workFlow.constant.Constant;
import com.ruoyi.workFlow.domain.ActTaskDTO;
import com.ruoyi.workFlow.domain.ActWorkflowFormData;
import com.ruoyi.workFlow.domain.dto.ActWorkflowFormDataDTO;
import com.ruoyi.workFlow.mapper.ActWorkflowFormDataMapper;
import com.ruoyi.workFlow.service.IProcessDefinitionService;
import com.ruoyi.workFlow.service.ITaskService;
import com.ruoyi.workFlow.service.OperationalWorkFlowService;
import com.ruoyi.worker.domain.*;
import com.ruoyi.worker.mapper.AttendanceGroupMapper;
import com.ruoyi.worker.mapper.AuditRecordMapper;
import com.ruoyi.worker.mapper.OperationNeedMapper;
import com.ruoyi.worker.mapper.OperationalManagementMapper;
import com.ruoyi.worker.service.AttendanceGroupService;
import com.ruoyi.worker.service.OperationalService;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.bpmn.model.*;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.activiti.engine.impl.persistence.entity.HistoricProcessInstanceEntityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName TaskServiceImpl
 * @Description 流程任务服务类
 * @Author leizhang
 * Date 2021/10/28 4:36 下午
 * @Version 1.0
 **/
@Service
public class TaskServiceImpl implements ITaskService {
    @Autowired
    private TaskRuntime taskRuntime;

    @Resource
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private AuditRecordMapper auditRecordMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private OperationNeedMapper operationNeedMapper;

    @Resource
    private OperationalManagementMapper operationalManagementMapper;

    @Resource
    private ActWorkflowFormDataMapper actWorkflowFormDataMapper;

    @Resource
    private OperationalService operationalService;

    @Autowired
    private AttendanceGroupService attendanceGroupService;

    @Autowired
    private HistoryService historyService;
    @Autowired
    private AttendanceGroupMapper attendanceGroupMapper;

    @Autowired
    private IProcessDefinitionService processDefinitionService;
    @Autowired
    private OperationalWorkFlowService operationalWorkFlowService;
    /**
     * @param requestMap
     * @return java.util.List<org.activiti.api.task.model.Task>
     * @Description : 个人任务列表查询
     * @Author : leizhang
     * @Date 4:43 下午 2021/10/26
     **/
    @Override
    public com.github.pagehelper.Page<ActTaskDTO> getTaskList(Map<String, Object> requestMap) {
        com.github.pagehelper.Page<ActTaskDTO> list = new com.github.pagehelper.Page<>();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<Task> pageTasks = taskRuntime.tasks(Pageable.of((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize()));
        List<Task> tasks = pageTasks.getContent();
        int totalItems = pageTasks.getTotalItems();
        list.setTotal(totalItems);
        if (totalItems != 0) {
            Set<String> processInstanceIdIds = tasks.parallelStream().map(t -> t.getProcessInstanceId()).collect(Collectors.toSet());
            List<org.activiti.engine.runtime.ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery().processInstanceIds(processInstanceIdIds).list();
            List<ActTaskDTO> actTaskDTOS = tasks.stream()
                    .map(t -> new ActTaskDTO(taskService.getVariables(t.getId()), t, processInstanceList.parallelStream().filter(pi -> t.getProcessInstanceId().equals(pi.getId())).findAny().get()))
                    .collect(Collectors.toList());
            list.addAll(actTaskDTOS);
        }
        return list;
    }

    /**
     * @param requestMap {"taskId":"任务id","businessKey":"业务关联主键id","taskType":"业务类型 默认运营需求单审核"}
     * @return void
     * @Description : 任务组任务拾取and完成
     * @Author : leizhang
     * @Date 5:31 下午 2021/10/26
     **/
    @Override
    public void completeTaskByTaskId(Map<String, Object> requestMap) {
        if (null == requestMap || requestMap.isEmpty()) {
            throw new IllegalArgumentException("请求参数异常");
        }
        String taskId = null;
        if (null == requestMap.get("businessKey") || null == requestMap.get("taskId") || StrUtil.isEmpty(taskId = requestMap.get("taskId").toString())) {
            throw new IllegalArgumentException("taskId或businessKey参数异常");
        }
        //任务拾取
        taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(taskId).build());
        //任务完成
        taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskId).build());
        //审核记录保存
        Integer taskType = null == requestMap.get("taskType") ? 1 : Integer.parseInt(requestMap.get("taskType").toString());
        requestMap.put("auditTime", new Date());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        requestMap.put("auditId", loginUser.getUserId());
        requestMap.put("auditName", loginUser.getUsername());
        requestMap.put("auditDeptId", loginUser.getDeptId());
        requestMap.put("auditDeptName", loginUser.getUser().getDept().getDeptName());
        requestMap.put("auditStatus", 1);
        requestMap.put("auditResult", 1);
        requestMap.put("auditType", taskType);
        requestMap.put("auditAffairId", requestMap.get("businessKey"));
        auditRecordMapper.addSysAuditRecord(requestMap);
    }

    @Override
    public List<String> formDataShow(String taskID) {
        Task task = taskRuntime.task(taskID);
        /**
         FormProperty_0ueitp2--__!!类型--__!!名称--__!!是否参数--__!!默认值
         例子：
         FormProperty_0lovri0--__!!string--__!!姓名--__!!f--__!!同意!!__--驳回 0 同意 1 不同意
         FormProperty_agree--__!!int--__!!--__!!s
         默认值：无、字符常量、FormProperty_开头定义过的控件ID
         */
        UserTask userTask = (UserTask) repositoryService.getBpmnModel(task.getProcessDefinitionId())
                .getFlowElement(task.getFormKey());
        if (userTask == null) {
            return null;
        }
        List<FormProperty> formProperties = userTask.getFormProperties();
        List<String> collect = formProperties.stream().map(fp -> fp.getId()).collect(Collectors.toList());
        return collect;
    }

    /**
     * @param taskID
     * @param awfs
     * @return int
     * @Description : 审批结果保存
     * @Author : leizhang
     * @Date 4:24 下午 2021/10/29
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int formDataSave2(String taskID, List<ActWorkflowFormDataDTO> awfs, Integer taskType) throws ParseException {
        Task task = taskRuntime.task(taskID);
        ExecutionEntityImpl processInstance = (ExecutionEntityImpl) runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        Boolean hasVariables = false;//没有任何参数
        HashMap<String, Object> variables = Maps.newHashMap();
        //前端传来的字符串，拆分成每个控件
        List<ActWorkflowFormData> acwfds = Lists.newArrayList();
        for (ActWorkflowFormDataDTO awf : awfs) {
            ActWorkflowFormData actWorkflowFormData = new ActWorkflowFormData(taskService.getVariables(task.getId()), processInstance, processInstance.getBusinessKey(), awf, task);
            acwfds.add(actWorkflowFormData);
            //构建参数集合
            if (!"f".equals(awf.getControlIsParam())) {
                variables.put(awf.getControlId(), awf.getControlValue());
                hasVariables = true;
            }
        }
        String businessId = processInstance.getBusinessKey().split("_")[1];

        if (task.getAssignee() == null) {
            taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
        }
        int agree = 0;
        boolean updateFlag = true;
        //操作记录保存
        actWorkflowFormDataMapper.insertActWorkflowFormDatas(SecurityUtils.getUsername(), acwfds, new Date(), SecurityUtils.getNickName());
        if (hasVariables) {
            variables.put(Constant.REASON, variables.get(Constant.FORM_PROPERTY_REMARK));
            //注：表单提交所有同意不同意按钮 表单格式同意使用 FormProperty_agree 0 表示同意  1表示不同意
            if (null != variables.get(Constant.FORM_PROPERTY_AGREE)) {
                agree = Integer.parseInt(variables.get(Constant.FORM_PROPERTY_AGREE).toString());
                if (1 == agree) {
                    //不同意 节点返回发起人
                    Map<String, Object> requestParam = Maps.newHashMap();
                    requestParam.put(Constant.TASK_ID, businessId);
                    requestParam.put(Constant.REASON, variables.get(Constant.FORM_PROPERTY_REMARK));
                    requestParam.put(Constant.AUDIT_RESULT, 3);
                    delProcessInstance(requestParam);
                    updateFlag = false;
                } else {
                    //判断节点是否为尾结点 尾结点 结束更新主表状态
                    if (isEnded(taskID)) {
                        updateFlag = false;
                        //流程实例结束,更新主表状态
                        Map<String, Object> requestParam = Maps.newHashMap();
                        requestParam.put(Constant.ID, Integer.parseInt(businessId));
                        requestParam.put(Constant.AUDIT_RESULT, 2);
                        requestParam.put(Constant.REASON, variables.get(Constant.FORM_PROPERTY_REMARK));
                        operationalService.updateAuditInfo(requestParam);
                        //下一个节点结束 且 当前节点不是总经理
                        if (!Constant.USER_TASK_ZJL.equals(this.isZjl(taskID))) {
                            //自动记录总经理审批记录信息...垃圾功能 特定化植入
                            ArrayList<ActWorkflowFormData> es = Lists.newArrayList();
                            for (ActWorkflowFormData ac : acwfds) {
                                es.add(ac);
                            }
                            saveZjlLog(taskType, variables, es, businessId);
                        }
                    }
                    //带参数完成任务
                    taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID)
                            .withVariables(variables)
                            .build());
                }
            }
        } else {
            taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID)
                    .build());
        }
        //审核记录保存
        if (updateFlag) {
            //尾结点已经操作了日志 所以这个地方不需要再次添加
            this.auditLogSave(variables, agree, taskType, businessId);
        }
        return 1;
    }

    //总经理自动保存
    private void saveZjlLog(Integer taskType, HashMap<String, Object> variables, List<ActWorkflowFormData> es, String businessId) {

        List<Map<String, Object>> roleUserName = actWorkflowFormDataMapper.getRoleUserName(Maps.newHashMap());
        if (!roleUserName.isEmpty()) {
            Map<String, Object> userMap = roleUserName.get(0);
            String zjlName = userMap.get("userName").toString();
            for (ActWorkflowFormData e : es) {
                if ("FormProperty_remark".equals(e.getControlId())) {
                    e.setControlValue("自动审批");
                    e.setTaskNodeName("总经理");
                }
                if ("FormProperty_agree".equals(e.getControlId())) {
                    e.setTaskNodeName("总经理");
                }
            }
            actWorkflowFormDataMapper.insertActWorkflowFormDatas(zjlName, es, new Date(), userMap.get("nickName").toString());
            variables.put("zjlName", zjlName);
            variables.put("zjlId", userMap.get("userId"));
            variables.put("zjlReason", "自动审批");
            auditLogSave(variables, 0, taskType, businessId);
        }
    }

    //审核记录保存
    private void auditLogSave(Map<String, Object> variables, int agree, Integer taskType, String businessId) {
        variables.put("auditTime", new Date());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        variables.put("auditId", null == variables.get("zjlId") ? loginUser.getUserId() : variables.get("zjlId"));
        variables.put("auditName", null == variables.get("zjlName") ? loginUser.getUsername() : variables.get("zjlName"));
        variables.put("auditDeptId", loginUser.getDeptId());
        if (null != variables.get("zjlName")) {
            //管理用户部门太麻烦了 直接写死
            variables.put("auditDeptName", "总经办");
        }else {
            variables.put("auditDeptName", null == loginUser.getUser().getDept() ? "" : loginUser.getUser().getDept().getDeptName());
        }
        variables.put("auditStatus", 1);
        //agree 1 是不同意  0 是同意 sys_audit 审核结果 1-待审核 2-审核通过 3-审核拒绝 4-审核撤销
        variables.put("auditResult", agree == 0 ? 2 : agree == 1 ? 3 : agree);
        variables.put("auditType", null == taskType ? 1 : taskType);
        variables.put("auditAffairId", businessId);
        variables.put("operationalStage",4);
        if (null != variables.get("zjlReason")) {
            variables.put("reason", variables.get("zjlReason"));
        }
        auditRecordMapper.addSysAuditRecord(variables);
    }

    private FlowElement currentNode(String taskId) {
        //获取当前任务
        org.activiti.engine.task.Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //获取当前模型
        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
        //获取当前节点（当前流程节点）
        FlowNode flowNode = (FlowNode) bpmnModel.getFlowElement(task.getTaskDefinitionKey());
        return flowNode;
    }

    //判断当前节点的下一个节点是否为尾结点
    private boolean isEnded(String taskId) {
        FlowNode flowNode = (FlowNode) currentNode(taskId);
        //输出连线
        List<SequenceFlow> outgoingFlows = flowNode.getOutgoingFlows();


        //遍历返回下一个节点信息
        for (SequenceFlow outgoingFlow : outgoingFlows) {
            //类型自己判断
            FlowElement targetFlowElement = outgoingFlow.getTargetFlowElement();
            //判断下一个节点类型是否为尾结点
            if (targetFlowElement instanceof EndEvent) {
                return true;
            }
        }
        return false;
    }

    //获取当前节点
    private String isZjl(String taskId) {
        UserTask userTask = (UserTask) this.currentNode(taskId);
        String formKey = userTask.getFormKey();
        return formKey;
    }

    /**
     * @param requestParam
     * @return void
     * @Description : 任务撤销
     * @Author : leizhang
     * @Date 9:44 下午 2021/11/4
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delProcessInstance(Map<String, Object> requestParam) {
        String taskId;
        if (StrUtil.isEmpty(taskId = requestParam.get("taskId").toString())) {
            throw new IllegalArgumentException("任务实例id为空");
        }
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey("yyxq_".concat(taskId)).singleResult();
        int auditResult = null == requestParam.get("auditResult") ? 0 : Integer.parseInt(requestParam.get("auditResult").toString());
        runtimeService.deleteProcessInstance(processInstance.getProcessInstanceId(), null == requestParam.get("reason") ? "" : requestParam.get("reason").toString());
        //更新数据库任务状态，activiti历史记录不清除
        //运行需求单 撤销操作
        OperationalRequirementsTable operationalRequirementsTable = operationalService.selectOperationalRequirementsTableById(Integer.valueOf(taskId));
        Integer status = 0;
        Integer taskNode = operationalRequirementsTable.getTaskNode();
        if (taskNode == 1){
            status = 0;
        }else if (taskNode == 2) {
            status = 3;
        }else if (taskNode == 3) {
            status = 6;
        }else if (taskNode == 4) {
            status = 6;
            taskNode = 3;
        }else if (taskNode == 5) {
            taskNode = 3;
            status = 6;
        }
        operationalService.updateOperationalById(new OperationalRequirementsTable(Integer.valueOf(taskId),status,taskNode,new Date()));
        Map<String,Object> logMap = Maps.newHashMap();
        logMap.put("reason","撤销审核");
        logMap.put("businessKey",taskId);
        logMap.put("result",4);
        logMap.put("taskNode",taskNode);
        saveLog(logMap);
    }

    /**
     * @param requestParam
     * @return java.util.List<org.activiti.api.task.model.Task>
     * @Description : 获取任务发起者信息
     * @Author : leizhang
     * @Date 11:23 上午 2021/11/6
     **/
    @Override
    public com.github.pagehelper.Page<ActTaskDTO> getProcessInfoByStart(Map<String, Object> requestParam) {
        com.github.pagehelper.Page<ActTaskDTO> list = new com.github.pagehelper.Page<>();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery().startedBy(SecurityUtils.getUserId().toString());
        List<HistoricProcessInstance> historicProcessInstances = historicProcessInstanceQuery.list();
        if (historicProcessInstances.size() != 0) {
            Set<String> processInstanceIds = Sets.newHashSet();
            for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
                String processInstanceId = ((HistoricProcessInstanceEntityImpl) historicProcessInstance).getProcessInstanceId();
                processInstanceIds.add(processInstanceId);
            }
            List<org.activiti.engine.runtime.ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery().processInstanceIds(processInstanceIds).list();
            if (processInstanceList.isEmpty()) {
                return list;
            }
            for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
                for (ProcessInstance processInstance : processInstanceList) {
                    if (((HistoricProcessInstanceEntityImpl) historicProcessInstance).getProcessInstanceId().toString().equals(processInstance.getProcessInstanceId())) {
                        list.add(new ActTaskDTO(historicProcessInstance, processInstance));
                    }
                }
            }
        }

        return list;
    }

    /**
     * @description:  临时工考勤审核流程
     * @author 刘松山
     * @date 2021/12/27 10:18
     *
     */
    @Override
    @Transactional
    public int tempsFlowSave(String taskID, List<ActWorkflowFormDataDTO> awfs,int taskType) throws ParseException {
        Task task = taskRuntime.task(taskID);
        ExecutionEntityImpl processInstance = (ExecutionEntityImpl) runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        Boolean hasVariables = false;//没有任何参数
        HashMap<String, Object> variables = Maps.newHashMap();
        //前端传来的字符串，拆分成每个控件
        List<ActWorkflowFormData> acwfds = Lists.newArrayList();
        for (ActWorkflowFormDataDTO awf : awfs) {
            ActWorkflowFormData actWorkflowFormData = new ActWorkflowFormData(taskService.getVariables(task.getId()), processInstance, processInstance.getBusinessKey(), awf, task);
            acwfds.add(actWorkflowFormData);
            //构建参数集合
            if (!"f".equals(awf.getControlIsParam())) {
                variables.put(awf.getControlId(), awf.getControlValue());
                hasVariables = true;
            }
        }
        String businessId = processInstance.getBusinessKey().split("_")[1];

        if (task.getAssignee() == null) {
            taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
        }
        int agree = 0;
        boolean updateFlag = true;
        //操作记录保存
        actWorkflowFormDataMapper.insertActWorkflowFormDatas(SecurityUtils.getUsername(), acwfds, new Date(), SecurityUtils.getNickName());
        if (hasVariables) {
            variables.put(Constant.REASON, variables.get(Constant.FORM_PROPERTY_REMARK));
            //注：表单提交所有同意不同意按钮 表单格式同意使用 FormProperty_agree 0 表示同意  1表示不同意
            if (null != variables.get(Constant.FORM_PROPERTY_AGREE)) {
                agree = Integer.parseInt(variables.get(Constant.FORM_PROPERTY_AGREE).toString());
                long id = Long.parseLong(businessId);
                AttendanceInfo info = new AttendanceInfo();
                info.setId(id);
                AttendanceInfo attendanceInfo =attendanceGroupService.getAttendanceStatistics(info);
                AttendanceGroup a = new AttendanceGroup();
                a.setWorkTime(attendanceInfo.getWorkTime());
                AttendanceGroup attendanceGroup = new AttendanceGroup();
                //不同意 1 同意 2
                if (1 == agree) {
                    //状态：审核驳回 3
                    //0 待确认 1 待处理  2 已经驳回 3  已确认
                    //修改明细表状态
                    a.setCheckFlag(2);
                    attendanceGroupMapper.modifyAttendanceSum(a);

                    //修改临时工汇总表状态
                    attendanceInfo.setStatus(2);
                    attendanceGroupMapper.modifyAttendanceInfo(attendanceInfo);
                    updateFlag = true;
                } else {
                    //判断节点是否为尾结点 尾结点 结束更新主表状态
                    if (isEnded(taskID)) {
                        updateFlag = true;
                        //流程实例结束,更新主表状态

                         //状态：已经确认 3
                        //0 待确认 1 待处理  2 已经驳回 3  已确认
                        //修改明细表状态
                        a.setCheckFlag(3);
                        attendanceGroupMapper.modifyAttendanceSum(a);

                        //修改临时工汇总表状态
                        attendanceInfo.setStatus(3);
                        attendanceGroupMapper.modifyAttendanceInfo(attendanceInfo);

                        //结算临时工工资
                        List<AttendanceInfo> attendanceInfos = attendanceGroupMapper.listAttendanceInfo(attendanceInfo);
                        if (attendanceInfos.size() > 0) {
                            //生成薪资明细
                            attendanceGroupService.translateAttendanceToSalary(attendanceInfos);
                        }

                    }

                }
                //带参数完成任务
                taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID)
                        .withVariables(variables)
                        .build());
            }
        } else {
            taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID)
                    .build());
        }
        //审核记录保存
        if (updateFlag) {
            //尾结点已经操作了日志 所以这个地方不需要再次添加
            this.auditLogSave(variables, agree, taskType, businessId);
        }
        return 1;
    }

    /**
     * @Description : 运营需求单保存
     * @Author : leizhang
     * @Date 7:24 PM 2021/12/27
     * @param taskID
 * @param awfs
 * @param taskType
     * @return int
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int formDataSave(String taskID, List<ActWorkflowFormDataDTO> awfs, Integer taskType) throws ParseException {
        Task task = taskRuntime.task(taskID);
        ExecutionEntityImpl processInstance = (ExecutionEntityImpl) runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        Boolean hasVariables = false;//没有任何参数
        HashMap<String, Object> variables = Maps.newHashMap();
        //前端传来的字符串，拆分成每个控件
        List<ActWorkflowFormData> acwfds = Lists.newArrayList();
        for (ActWorkflowFormDataDTO awf : awfs) {
            ActWorkflowFormData actWorkflowFormData = new ActWorkflowFormData(taskService.getVariables(task.getId()), processInstance, processInstance.getBusinessKey(), awf, task);
            acwfds.add(actWorkflowFormData);
            //构建参数集合
            if (!"f".equals(awf.getControlIsParam())) {
                variables.put(awf.getControlId(), awf.getControlValue());
                hasVariables = true;
            }
        }
        String businessId = processInstance.getBusinessKey().split("_")[1];

        Integer id = Integer.parseInt(businessId);
        OperationalRequirementsTable operationalRequirementsTable = operationalService.selectOperationalRequirementsTableById(id);
        Integer taskNode = operationalRequirementsTable.getTaskNode();

        if (task.getAssignee() == null) {
            taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
        }
        int agree = 0;
        boolean isEndFlag = false;
        //操作记录保存
        actWorkflowFormDataMapper.insertActWorkflowFormDatas(SecurityUtils.getUsername(), acwfds, new Date(), SecurityUtils.getNickName());
        if (hasVariables) {
            variables.put(Constant.REASON, variables.get(Constant.FORM_PROPERTY_REMARK));
            //注：表单提交所有同意不同意按钮 表单格式同意使用 FormProperty_agree 0 表示同意  1表示不同意
            if (null != variables.get(Constant.FORM_PROPERTY_AGREE)) {
                agree = Integer.parseInt(variables.get(Constant.FORM_PROPERTY_AGREE).toString());
                if (1 == agree) {
                    //不同意 节点返回发起人
                    Map<String, Object> requestParam = Maps.newHashMap();
                    requestParam.put(Constant.TASK_ID, businessId);
                    requestParam.put(Constant.REASON, variables.get(null == Constant.FORM_PROPERTY_REMARK ? "" : Constant.FORM_PROPERTY_REMARK));
                    requestParam.put(Constant.AUDIT_RESULT, 3);
                    delProcessInstance(requestParam);
                } else {
                    boolean flag = Constant.USER_TASK_ZJL.equals(this.isZjl(taskID));
                    if (isEndFlag = isEnded(taskID)) {
                        //流程实例结束,更新主表状态
                        if (taskNode == 4 && !flag) {
                            //自动记录总经理审批记录信息...垃圾功能 特定化植入
                            ArrayList<ActWorkflowFormData> es = Lists.newArrayList();
                            for (ActWorkflowFormData ac : acwfds) {
                                es.add(ac);
                            }
                            saveZjlLog(taskType, variables, es, businessId);
                        }
                    }
                    //带参数完成任务
                    taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID)
                            .withVariables(variables)
                            .build());
                }
            }
        } else {
            taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID)
                    .build());
        }

        //节点等于3 并且审核通过 直接开启下一个 4节点
        if (taskNode == 3 && agree == 0) {
            OperationalRequirementsTable operationalRequirementsTable1 = operationalService.selectOperationalRequirementsTableById(Integer.parseInt(businessId));
            //启动流程
            Map<String, Object> requestParam = Maps.newHashMap();
            requestParam.put("processDefinitionKey", "yyxq_event");
            requestParam.put("processType", 1);
            requestParam.put("processInstanceName", "运营需求单审核");
            requestParam.put("businessKey",businessId);
            Map<String, Object> variablesis= Maps.newHashMap();
            variablesis.put("auditFlag", 4);
            variablesis.put("orderCode",operationalRequirementsTable1.getOperationalOrderCode());
            //计算是否总经理审批 建议人数/预估用人数 > 用工超控比
            Double personnelExcessPercentage = operationalRequirementsTable1.getPersonnelExcessPercentage();
            Double personnelOverridePercentage = operationalRequirementsTable1.getPersonnelOverridePercentage();
            variablesis.put("auditFlagZjl",1);
            requestParam.put("variables", variablesis);
            operationalWorkFlowService.startOperationalWorkFlowProcess(requestParam);
            //更新状态
            operationalService.updateOperationalById(new OperationalRequirementsTable(Integer.valueOf(businessId),9,4,new Date()));
        }
        //业务处理
        //1.根据业务查询业务信息
        //2.同意节点往后累加，不同意节点往前回退
        //3.status 转态处理
        Integer status = 0;
        if (1 == agree) {
            //获取当前节点
            if (taskNode ==1 ) {
                status = 2;
            }else if (taskNode == 2) {
                status = 5;
            }else if (taskNode == 3) {
                status = 8;
            }else if (taskNode == 4) {
                status = 8;
            }else if (taskNode == 5) {
                status = 8;
            }

            //不同意 节点倒退，status更新为驳回
            taskNode = taskNode == 5 || taskNode == 4 ?  3 : taskNode;
        }else {
            // 同意，下个节点待处理
            //获取当前节点
            if (taskNode == 4 && isEndFlag) {
                status = 10;
                taskNode++;
            }else if (taskNode == 4 && !isEndFlag) {
                status = 9;
            }
            if (taskNode ==1 ) {
                status = 3;
                taskNode++;
            }else if (taskNode == 2) {
                status = 6;
                taskNode++;
            }else if (taskNode == 3) {
                status = 9;
                taskNode++;
            }
        }
        operationalService.updateOperationalById(new OperationalRequirementsTable(id,status,taskNode,new Date()));
        Map<String,Object> logMap = Maps.newHashMap();
        logMap.put("reason",variables.get(Constant.REASON));
        logMap.put("businessKey",businessId);
        logMap.put("result",agree);
        logMap.put("taskNode",taskNode);
        saveLog(logMap);

        if (taskNode == 5 && agree == 0) {

            //审核通过新增用工分配渠道人数
            OperationalRequirementsTable operationalRequirementsTable1 = operationalService.selectOperationalRequirementsTableById(Integer.parseInt(businessId));
            //获取班次列表
            List<Map<String,Object>> timeShiftTypeMapList = operationNeedMapper.getTimeShiftType();
            StaffAssignmentsPojo staffAssignmentsPojo = new StaffAssignmentsPojo();
            staffAssignmentsPojo.setUpdateTime(new Date());
            int womanNumberScale = (int)(Math.round( operationalRequirementsTable1.getOddJobFemale()*operationalRequirementsTable1.getPersonnelOddNumber()/100));
            int manNumberScale =(int)(Math.round(operationalRequirementsTable1.getOddJobMale()*operationalRequirementsTable1.getPersonnelOddNumber()/100));
            staffAssignmentsPojo.setWomanNumberScale(womanNumberScale);
            staffAssignmentsPojo.setManNumberScale(manNumberScale);
            staffAssignmentsPojo.setCreateTime(new Date());
            staffAssignmentsPojo.setOperationNeedId(operationalRequirementsTable1.getId());
            staffAssignmentsPojo.setNeedTime(new SimpleDateFormat("yyyy-MM-dd").format(operationalRequirementsTable1.getWorkTime()));
            staffAssignmentsPojo.setTaskNumber(operationalRequirementsTable1.getOperationalOrderCode());
            for (Map<String,Object> map:timeShiftTypeMapList) {
                String timeShiftName = map.get("name") + "";
                if(timeShiftName.equals(operationalRequirementsTable1.getTimeShiftName())){
                    staffAssignmentsPojo.setTimeShiftId(Integer.parseInt(map.get("id")+""));
                    break;
                }

            }

            operationNeedMapper.addStaffAssignments(staffAssignmentsPojo);
            //获取渠道商分配情况
            List<Map<String,Object>> companyMapList = operationNeedMapper.getCompanyData();


            List<StaffAssignmentsDetailPojo> addStaffAssignmentsDetailList = new ArrayList<>();

                for (int j = 0; j < companyMapList.size(); j++) {
                    StaffAssignmentsDetailPojo staffAssignmentsDetailPojo = new StaffAssignmentsDetailPojo();
                    staffAssignmentsDetailPojo.setStaffAssignmentsId(staffAssignmentsPojo.getStaffAssignmentsId());
                    for (int i = 0; i < timeShiftTypeMapList.size(); i++) {
                        Map<String, Object> map = timeShiftTypeMapList.get(i);
                        String timeShiftName = map.get("name") + "";
                        Integer timeShiftType = Integer.parseInt(map.get("type") + "");
                        if(timeShiftName.equals(operationalRequirementsTable1.getTimeShiftName())){
                            staffAssignmentsDetailPojo.setTimeShiftName(timeShiftName);
                            staffAssignmentsDetailPojo.setType(timeShiftType);
                            break;
                        }

                    }
                    Map<String, Object> companyMap = companyMapList.get(j);
                    Integer companyId = Integer.parseInt(companyMap.get("id")+"");
                    String company = companyMap.get("company")+"";
                    String rStr = companyMap.get("recruitPercent")+"";
                    if ("".equals(rStr)||"null".equals(rStr)){
                        rStr = "0";
                    }
                    double recruitPercent = Double.parseDouble(rStr);
                    double manNumberfloor =  Math.floor((operationalRequirementsTable1.getOddJobMale()
                            * recruitPercent
                            * operationalRequirementsTable1.getPersonnelOddNumber()
                          )/ 10000);
                    double womanNumberfloor =Math.floor( (operationalRequirementsTable1.getOddJobFemale()
                            * recruitPercent
                            * operationalRequirementsTable1.getPersonnelOddNumber()
                         )/ 10000);
                    int manNumber = (int) manNumberfloor;
                    int womanNumber = (int) womanNumberfloor;
                    staffAssignmentsDetailPojo.setCompanyId(companyId);
                    staffAssignmentsDetailPojo.setCompanyName(company);
                    staffAssignmentsDetailPojo.setManScale(recruitPercent);
                    staffAssignmentsDetailPojo.setWomanScale(recruitPercent);
                    staffAssignmentsDetailPojo.setManNumber(manNumber);
                    staffAssignmentsDetailPojo.setWomanNumber(womanNumber);
                    addStaffAssignmentsDetailList.add(staffAssignmentsDetailPojo);
                }


            if (addStaffAssignmentsDetailList.size()>0){
                operationNeedMapper.addStaffAssignmentsDetailPojo(addStaffAssignmentsDetailList);
            }


        }
        return 1;
    }

    private void saveLog(Map<String,Object> requestMap){
        Integer taskType = null == requestMap.get("taskType") ? 1 : Integer.parseInt(requestMap.get("taskType").toString());
        requestMap.put("auditTime", new Date());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        requestMap.put("auditId", loginUser.getUserId());
        requestMap.put("auditName", loginUser.getUsername());
        requestMap.put("auditDeptId", null == loginUser.getDeptId() ? null: loginUser.getDeptId());
        requestMap.put("auditDeptName", null == loginUser.getUser().getDept()? null:loginUser.getUser().getDept().getDeptName());
        requestMap.put("auditStatus", 1);
        //2-审核通过 3-审核拒绝
        requestMap.put("auditResult", requestMap.get("result").equals(0)?2:requestMap.get("result").equals(1)?3:4);
        requestMap.put("auditType", taskType);
        requestMap.put("auditAffairId", requestMap.get("businessKey"));
        requestMap.put("reason", requestMap.get("reason"));
        requestMap.put("operationalStage",null == requestMap.get("taskNode")?null:Integer.parseInt(requestMap.get("taskNode").toString()) -1);
        auditRecordMapper.addSysAuditRecord(requestMap);
    }
}
